import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:ideology/features/models/editor_status.dart';
import 'package:ideology/features/models/editor_tab.dart';
import 'package:ideology/shared/services/file_service.dart';
import 'package:ideology/shared/widgets/file_explorer/file_explorer_controller.dart';
import 'package:ideology/shared/widgets/file_explorer/file_node.dart';

/// 标签页管理器
///
/// 负责：
/// - 打开/关闭/切换标签页
/// - 管理文件与内存中 `EditorTab` 的同步（读/写/刷新）
/// - 与自动保存、文件监听/轮询对接
/// - 更新编辑器状态（行、列、字符数）并通知 UI
class TabManager {
  TabManager({
    required FileService fileService,
    required ValueNotifier<List<EditorTab>> tabs,
    required ValueNotifier<int> activeTabIndex,
    required ValueNotifier<EditorStatus> status,
    required String? Function() getProjectRootPath,
    required FileExplorerController explorerController,
    required void Function(EditorTab) registerAutoSave,
    required void Function(EditorTab) unregisterAutoSave,
    required void Function(EditorTab) startWatchForTab,
    required void Function(EditorTab) stopWatchForTab,
    required Future<void> Function(EditorTab, {bool immediate}) startPollForTab,
    required void Function(EditorTab) stopPollForTab,
    required VoidCallback onNotify,
  })  : _fileService = fileService,
        _tabs = tabs,
        _activeTabIndex = activeTabIndex,
        _status = status,
        _getProjectRootPath = getProjectRootPath,
        _registerAutoSave = registerAutoSave,
        _unregisterAutoSave = unregisterAutoSave,
        _startWatchForTab = startWatchForTab,
        _stopWatchForTab = stopWatchForTab,
        _startPollForTab = startPollForTab,
        _stopPollForTab = stopPollForTab,
        _onNotify = onNotify;

  // ─────────────────────────────── Fields ───────────────────────────────
  final FileService _fileService;
  final ValueNotifier<List<EditorTab>> _tabs;
  final ValueNotifier<int> _activeTabIndex;
  final ValueNotifier<EditorStatus> _status;
  final String? Function() _getProjectRootPath;

  final void Function(EditorTab) _registerAutoSave;
  final void Function(EditorTab) _unregisterAutoSave;
  final void Function(EditorTab) _startWatchForTab;
  final void Function(EditorTab) _stopWatchForTab;
  final Future<void> Function(EditorTab, {bool immediate}) _startPollForTab;
  final void Function(EditorTab) _stopPollForTab;

  final VoidCallback _onNotify;

  // ─────────────────────────────── Public API ───────────────────────────────

  /// 打开文件 [treePath] 并创建/激活标签页
  ///
  /// - 若文件已在标签中打开，则直接切换
  /// - 否则读取文件内容，创建新标签页并启动自动保存、监听与轮询
  Future<void> openFile(String treePath, FileNode node) async {
    if (node.isFolder) return;
    final root = _getProjectRootPath();
    if (root == null) return;

    final parts = treePath.split('/');
    final rel = parts.length > 1 ? parts.sublist(1).join('/') : '';
    final fullPath = rel.isEmpty ? root : _fileService.join(root, rel);

    debugPrint('[TabManager] openFile → $fullPath');

    final existingIndex = _tabs.value.indexWhere((t) => t.fullPath == fullPath);
    if (existingIndex != -1) {
      debugPrint('[TabManager] file already open, switch to tab $existingIndex');
      setActiveTab(existingIndex);
      return;
    }

    final content = await _fileService.readAsString(fullPath);
    final title = _fileService.basename(fullPath);

    final tab = EditorTab(
      title: title,
      relativePath: rel,
      fullPath: fullPath,
      initialText: content,
    );

    _registerAutoSave(tab);
    _startWatchForTab(tab);
    await _startPollForTab(tab, immediate: true);

    _tabs.value = [..._tabs.value, tab];
    setActiveTab(_tabs.value.length - 1);
  }

  /// 关闭指定索引的标签页
  ///
  /// - 停止该标签页的自动保存、文件监听与轮询
  /// - 移除标签页并更新激活索引与状态
  /// - 在下一帧释放资源
  void closeTabAt(int index) {
    debugPrint('[TabManager] closeTabAt index=$index len=${_tabs.value.length}');
    if (index < 0 || index >= _tabs.value.length) {
      debugPrint('[TabManager] ❌ index out of range, abort');
      return;
    }

    // 1) 拷贝并移除
    final List<EditorTab> list = List<EditorTab>.from(_tabs.value);
    final removed = list.removeAt(index);
    debugPrint('[TabManager] → removed: ${removed.fullPath}');

    // 2) 停止后台任务
    _unregisterAutoSave(removed);
    _stopWatchForTab(removed);
    _stopPollForTab(removed);

    // 3) 更新 tabs，让 UI 重建
    _tabs.value = list;
    debugPrint('[TabManager] tabs updated, newLen=${list.length}');

    // 4) 重新计算激活索引
    if (list.isEmpty) {
      _activeTabIndex.value = -1;
      _status.value = const EditorStatus();
    } else {
      final current = _activeTabIndex.value;
      if (current == index) {
        // 关闭的是当前标签
        _activeTabIndex.value = index < list.length ? index : list.length - 1;
      } else if (current > index) {
        // 关闭的在当前激活标签之前，索引左移
        _activeTabIndex.value = current - 1;
      }
      updateStatusFromActive();
    }
    _onNotify();

    // 5) 下一帧再 dispose，避免 “used after dispose”
    WidgetsBinding.instance.addPostFrameCallback((_) {
      debugPrint('[TabManager] dispose removed tab (post-frame)');
      removed.dispose();
    });
  }

  /// 关闭所有标签页
  void closeAllTabs() {
    debugPrint('[TabManager] closeAllTabs (count=${_tabs.value.length})');
    for (final t in _tabs.value) {
      _unregisterAutoSave(t);
      _stopWatchForTab(t);
      _stopPollForTab(t);
    }
    final List<EditorTab> oldTabs = List<EditorTab>.from(_tabs.value);
    _tabs.value = <EditorTab>[];
    _activeTabIndex.value = -1;
    _status.value = const EditorStatus();
    _onNotify();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      for (final t in oldTabs) {
        t.dispose();
      }
    });
  }

  /// 设置激活的标签页索引
  void setActiveTab(int index) {
    if (index < 0 || index >= _tabs.value.length) return;
    _activeTabIndex.value = index;
    updateStatusFromActive();
    _onNotify();
  }

  // ─────────────────────────────── Helpers ───────────────────────────────

  /// 从当前激活标签页更新 [EditorStatus]
  void updateStatusFromActive() {
    final t = activeTab;
    if (t == null) {
      _status.value = const EditorStatus();
    } else {
      final text = t.text.value;
      _status.value = EditorStatus(line: 1, column: 1, charCount: text.length);
    }
  }

  /// 获取当前激活的标签页
  EditorTab? get activeTab {
    final idx = _activeTabIndex.value;
    if (idx < 0 || idx >= _tabs.value.length) return null;
    return _tabs.value[idx];
  }

  /// 刷新当前激活标签页的内容（从磁盘读取）
  Future<bool> refreshActiveTabFromDisk({bool force = false}) async {
    final tab = activeTab;
    if (tab == null) return false;
    return refreshFileByPath(tab.fullPath, force: force);
  }

  /// 根据路径刷新标签页内容
  ///
  /// - 若 [force] 为 false 且文件被标记为 `dirty`，则跳过刷新
  /// - 刷新成功则更新文本与状态，并返回 true
  Future<bool> refreshFileByPath(String fullPath, {bool force = false}) async {
    final idx = _tabs.value.indexWhere((t) => t.fullPath == fullPath);
    if (idx < 0) return false;
    final tab = _tabs.value[idx];

    if (!force && tab.dirty.value) {
      debugPrint('[TabManager] skip refresh, dirty=true');
      return false;
    }

    try {
      final fresh = await _fileService.readAsString(fullPath);
      tab.text.value = fresh;
      tab.dirty.value = false;
      if (_activeTabIndex.value == idx) {
        updateStatusFromActive();
      }
      _onNotify();
      debugPrint('[TabManager] file refreshed from disk');
      return true;
    } catch (e, st) {
      debugPrint('[TabManager] refresh failed: $e\n$st');
      return false;
    }
  }
}
